package net.bblot.lottery.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.karics.library.zxing.android.CaptureActivity;
import com.marsscp.cp.BuildConfig;
import com.umeng.analytics.MobclickAgent;
import com.umeng.analytics.game.UMGameAgent;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import net.bblot.lottery.PackegeConfig;

import com.marsscp.cp.R;

import net.bblot.lottery.api.request.GetWebUpdate;
import net.bblot.lottery.util.AdsPopwindowUtil;
import net.bblot.lottery.util.AppConfig;
import net.bblot.lottery.util.GetCropPhotoUtil;
import net.bblot.lottery.util.ImageUtils;
import net.bblot.lottery.util.Logger;
import net.bblot.lottery.util.ToastUtill;
import net.bblot.lottery.util.UrlUtils;
import net.bblot.lottery.util.WifiUtil;
import net.bblot.lottery.webInterface.WebInterface;
import net.bblot.lottery.webInterface.WebInvoke;
import net.bblot.lottery.wxapi.WXPayEntryActivity;

import org.apache.cordova.CordovaActivity;
import org.apache.cordova.UrlRedirectListener;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class BaseDroidGapActivity extends CordovaActivity implements UrlRedirectListener {
    public final static int RequestCode_ScanQRCode = 101;
    public final static int REQUEST_CODE_PERMISSION_QR_CODE = 201;

    /**
     * 扫码类型
     */
    private String scanType = "";
    protected UMShareListener mUMShareListener;
    protected UMAuthListener authListener;
    protected ShareAction sa;
    public WebInterface webInterface;
    public WebInvoke webInvoke;
    protected Dialog splashDialog;
    protected Drawable drawable = null;
    // 一些广播监听，例如下载apk的更新等
    private BroadcastReceiver br_download;
    // wifi网络状态的监听
    private BroadcastReceiver br_wifi;
    // 微信支付的回调监听
    private BroadcastReceiver br_wxPay;

    // 用于分享的回调
    private String share_pageId = "";
    public GetCropPhotoUtil gpu;
    public String num;
    public String photo_type;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        net.bblot.lottery.activity.AppManager.getAppManager().addActivity(this);
        gpu = new GetCropPhotoUtil(BaseDroidGapActivity.this);
        //设置场景类型
        MobclickAgent.setScenarioType(this, MobclickAgent.EScenarioType.E_UM_GAME);
        UMGameAgent.init(this);
    }

    @Override
    public void init() {
        // TODO Auto-generated method stub
        super.init();
        initSocialShare();
        init_WebView();
        init_receiver();
    }

    /**
     * 获取第三方平台信息，用于第三方登录
     */
    public void getPlatformInfo(String type, String platform, String id, String secret) {

        UMShareAPI mShareAPI = UMShareAPI.get(getApplicationContext());

        SHARE_MEDIA media;

        authListener = new MyUMAuthListener(type);

        if (platform.equals("wx")) {
            // 微信
            media = SHARE_MEDIA.WEIXIN;
            PlatformConfig.setWeixin(id, secret);

            // 先 deleteOauth，再 doOauthVerify，可以重新弹出授权页面
            mShareAPI.deleteOauth(this, media, null);
//            mShareAPI.doOauthVerify(this, media, authListener);

            mShareAPI.getPlatformInfo(this, media, authListener);

        } else if (platform.equals("qq")) {
            // qq
            media = SHARE_MEDIA.QQ;
            PlatformConfig.setQQZone(id, secret);

            // mShareAPI.doOauthVerify(this, media, authListener);

            mShareAPI.getPlatformInfo(this, media, authListener);
            // mShareAPI.deleteOauth(this, media, null);
        }
    }

    @Override
    public void onUrlJumpWechat(String url) {

    }

    @Override
    public void onUrlJumpCustom(String url) {

    }

    @Override
    public void onUrlJumpAliPay(String url) {

    }

    /**
     * 代码 copy 自 http://dev.umeng.com/social/android/quick-integration#3_1，liuchao
     */
    class MyUMAuthListener implements UMAuthListener {

        public String type;

        public MyUMAuthListener(String type) {
            this.type = type;
        }

        /**
         * 授权开始的回调
         *
         * @param platform 平台名称
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
        }

        /**
         * 授权成功的回调
         *
         * @param platform 平台名称
         * @param action   行为序号，开发者用不上
         * @param data     用户资料返回
         */
        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            String media = "";
            switch (platform) {
                case WEIXIN:
                    media = "wx";
                    break;
                case QQ:
                    media = "qq";
                    break;
            }

            String uid = data.get("uid");
            String name = data.get("name");
            String iconurl = data.get("iconurl");

//            Gson gson = new Gson();
//            Toast.makeText(getApplicationContext(), gson.toJson(data), Toast.LENGTH_LONG).show();

            Toast.makeText(getApplicationContext(), "登录成功", Toast.LENGTH_LONG).show();

            UMShareAPI mShareAPI = UMShareAPI.get(getApplicationContext());
            mShareAPI.deleteOauth(BaseDroidGapActivity.this, platform, null);

            webInvoke.socialAuthCallBack(type, media, uid, name, iconurl);
        }

        /**
         * 授权失败的回调
         *
         * @param platform 平台名称
         * @param action   行为序号，开发者用不上
         * @param t        错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Toast.makeText(getApplicationContext(), "授权失败", Toast.LENGTH_LONG).show();
        }

        /**
         * 授权取消的回调
         *
         * @param platform 平台名称
         * @param action   行为序号，开发者用不上
         */
        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
//             Toast.makeText(getApplicationContext(), "取消授权", Toast.LENGTH_LONG).show();
        }
    }

    public void setScanType(String type) {
        this.scanType = type;
    }

    protected void initSocialAuth() {
//        PlatformConfig.setWeixin(PackegeConfig.WEIXIN_APPID, PackegeConfig.WEIXIN_APPSecret);
//        PlatformConfig.setQQZone(PackegeConfig.QQ_APPID, PackegeConfig.QQ_APPSecret);

        // TODO 代码 copy 自 http://dev.umeng.com/social/android/quick-integration#3_1，liuchao
//        authListener = new MyUMAuthListener("") {};
    }


    protected void init_receiver() {
        // TODO Auto-generated method stub
        br_download = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                // TODO Auto-generated method stub
                long completeDownloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,
                        -1);
                long reference = AppConfig.getDownLoadReference(context);
                if (reference != completeDownloadId) {
                    return;
                }
                try {
                    File file = new File(AppConfig.getlatestVersionPath(context));
                    if (file.exists()) {
                        Intent intent_install = new Intent();
                        intent_install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent_install.setAction(Intent.ACTION_VIEW);
                        String type = "application/vnd.android.package-archive";
                        intent_install.setDataAndType(Uri.fromFile(file), type);
                        startActivity(intent_install);
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                }

            }
        };
        IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        registerReceiver(br_download, intentFilter);

        br_wifi = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                // TODO Auto-generated method stub
                noticeWifiStatusChange();
            }
        };
        IntentFilter intentFilter_wifi = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(br_wifi, intentFilter_wifi);

        br_wxPay = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, final Intent intent) {
                appView.getView().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        int errcode = intent.getIntExtra(WXPayEntryActivity.KEY_errcode, -1);
                        webInvoke.getPayWeixinCallback(errcode + "");
//						ToastUtill.showToast(getApplicationContext(),"errcode="+errcode);
                    }
                }, 1000);
            }
        };
        IntentFilter intentFilter_wxPay = new IntentFilter(WXPayEntryActivity.WXPay);
        registerReceiver(br_wxPay, intentFilter_wxPay);
    }

    public void noticeWifiStatusChange() {
        this.appView.getView().postDelayed(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                String ssid = WifiUtil.getWifiState(getApplicationContext());
                if (TextUtils.isEmpty(ssid)) {
                    webInvoke.noticeWifiStatusChange(-1, "");
                } else {
                    webInvoke.noticeWifiStatusChange(1, ssid);
                }
            }
        }, 1000);

    }


    @SuppressLint("NewApi")
    private void init_WebView() {
        // TODO Auto-generated method stub
        webInterface = new WebInterface(this);
        WebView webView = (WebView) this.appView.getView();
        webView.addJavascriptInterface(webInterface, "android_obj");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
        }

        webInvoke = new WebInvoke(this);

        appView.setUrlRedirectListener(this);
    }


    protected void showSplashScreen(int time, onSplashScreenCloseListener listener) {
        // TODO Auto-generated method stub
        if (drawable == null) {
            drawable = getResources().getDrawable(R.drawable.screen);
            showSplashScreen(drawable, time, listener);
        } else {
            showSplashScreen(drawable, time, listener);

        }
    }

    public interface onSplashScreenCloseListener {
        void onClose(boolean refresh);
    }


    public void removeSplashScreen() {
        Logger.e(TAG, "removeSplashScreen");
        // TODO Auto-generated method stub
        if (splashDialog != null && splashDialog.isShowing()) {
            try {
                AdsPopwindowUtil.setStopTime();
            } catch (Exception e) {
                e.printStackTrace();
            }
            splashDialog.dismiss();
        }
    }

    /**
     * Shows the splash screen over the full Activity
     */
    @SuppressWarnings("deprecation")
    public void showSplashScreen(final Drawable drawable, final int time, final onSplashScreenCloseListener listener) {
        final CordovaActivity that = this;

        final Runnable runnable = new Runnable() {
            private boolean updateEnd = false;
            private boolean refresh = false;
            View root;
            ProgressBar progressBar;
            TextView message;

            public void run() {
                updateEnd = false;
                // Set Runnable to remove splash screen just in case
                final Handler handler = new Handler();
                // Get reference to display
                Display display = getWindowManager().getDefaultDisplay();

                // Create the layout for the dialog
//                LinearLayout root = new LinearLayout(BaseDroidGapActivity.this);
//                root.setMinimumHeight(display.getHeight());
//                root.setMinimumWidth(display.getWidth());
//                root.setOrientation(LinearLayout.VERTICAL);
////				root.setBackgroundColor(getIntegerProperty("backgroundColor", Color.BLACK));
//                root.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams
//                        .FILL_PARENT,
//                        ViewGroup.LayoutParams.FILL_PARENT, 0.0F));
//                root.setBackgroundDrawable(drawable);

                root = getLayoutInflater().inflate(R.layout.layout, null);
                root.setBackgroundResource(BuildConfig.Splash);
                progressBar = (ProgressBar) root.findViewById(R.id.progress_bar);
                message = (TextView) root.findViewById(R.id.message);

                // Create and show the dialog
                splashDialog = new Dialog(that, android.R.style.Theme_Translucent_NoTitleBar);
                // check to see if the splash screen should be full screen
                if ((getWindow().getAttributes().flags
                        & WindowManager.LayoutParams.FLAG_FULLSCREEN) == WindowManager
                        .LayoutParams.FLAG_FULLSCREEN) {
                    splashDialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                            WindowManager.LayoutParams.FLAG_FULLSCREEN);
                }
                splashDialog.setContentView(root);
                splashDialog.setCancelable(false);
                splashDialog.show();

                GetWebUpdate.checkWebUpdate(getApplicationContext(), new GetWebUpdate.SimpleUpdateListener() {

                    @Override
                    public void onDownloadStart() {
                        super.onDownloadStart();
                        progressBar.setVisibility(View.VISIBLE);
                    }

                    @Override
                    public void onDownloadPercent(int per) {
                        super.onDownloadPercent(per);
                        Logger.e(TAG, "下载进度" + per);
                        progressBar.setProgress(per);
                        message.setText("资源加载中：" + per + "%");
                    }

                    @Override
                    public void onUnzipStart() {
                        super.onUnzipStart();
                        Logger.e(TAG, "开始解压");
                        message.setText("正在解压资源...");
                    }

                    @Override
                    public void onUnzipEnd(boolean result) {
                        super.onUnzipEnd(result);
                        Logger.e(TAG, "解压结束");
                        if (result) {
                            message.setText("资源解压成功");
                        } else {
                            message.setText("资源解压失败");
                        }
                    }

                    @Override
                    public void onFinish(int result) {
                        Logger.e(TAG, "更新结束" + result);
                        if (result == GetWebUpdate.UpdateListener.RES_SUCCESS) {
                            message.setText("更新成功");
                            refresh = true;

                        } else if (result == GetWebUpdate.UpdateListener.RES_NO_UPDATE) {
                            //message.setText("已经是最新版本");

                        } else if (result == GetWebUpdate.UpdateListener.RES_NET_ERROR) {
                            //message.setText("网络异常");
                        }
                        updateEnd = true;
                    }
                });

                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        try {
                            Thread.sleep(time);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        while (!updateEnd) {
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (listener != null) {
                                    listener.onClose(refresh);
                                }
                                removeSplashScreen();
                            }
                        });

                    }
                }.start();

//                handler.postDelayed(new Runnable() {
//                    public void run() {
//                        while (!updateEnd) {
//                            try {
//                                Thread.sleep(100);
//                            } catch (InterruptedException e) {
//                                e.printStackTrace();
//                            }
//                        }
//                        removeSplashScreen();
//                    }
//                }, time);
            }
        };
        this.runOnUiThread(runnable);
    }

    @Override
    protected void onResume() {
        MobclickAgent.onResume(this);
        UMGameAgent.onResume(this);
        super.onResume();

    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        MobclickAgent.onPause(this);
        UMGameAgent.onPause(this);
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (br_download != null) {
            unregisterReceiver(br_download);
        }
        if (br_wifi != null) {
            unregisterReceiver(br_wifi);
        }
        if (br_wxPay != null) {
            unregisterReceiver(br_wxPay);
        }
        gpu = null;
        // 结束Activity&从堆栈中移除
        net.bblot.lottery.activity.AppManager.getAppManager().finishActivity(this);
    }

    protected void initSocialShare() {
        // 添加微信平台
        //Config.DEBUG = true;//打开友盟调试
        PlatformConfig.setWeixin(PackegeConfig.WEIXIN_APPID, PackegeConfig.WEIXIN_APPSecret);
        PlatformConfig.setQQZone(PackegeConfig.QQ_APPID, PackegeConfig.QQ_APPSecret);

        mUMShareListener = new UMShareListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {

            }

            @Override
            public void onResult(SHARE_MEDIA share_media) {
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        webInvoke.shareSucess(share_pageId);

                    }
                }, 1000);
            }

            @Override
            public void onError(SHARE_MEDIA share_media, Throwable throwable) {

            }

            @Override
            public void onCancel(SHARE_MEDIA share_media) {

            }
        };

        sa = new ShareAction(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_PERMISSION_QR_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Intent intent = new Intent(this, CaptureActivity.class);
                intent.putExtra(CaptureActivity.KEY_TYPE, scanType);
                startActivityForResult(intent, BaseDroidGapActivity.RequestCode_ScanQRCode);
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        if (requestCode == RequestCode_ScanQRCode && resultCode == RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(CaptureActivity.KEY_CodedContent);
                String type = data.getStringExtra(CaptureActivity.KEY_TYPE);
                String sid = UrlUtils.parseParms(content, "station_id");
//				 Toast.makeText(getApplicationContext(),"type="+type+""+sid+ "" + content,
//				 Toast.LENGTH_SHORT).show();
                if (!TextUtils.isEmpty(sid) && "register".equals(type)) {
                    webInvoke.getScanQRCodeCallback(type, sid);
                } else {
                    ToastUtill.showToast(getApplicationContext(), "二维码有误,请联系二维码提供方");
                }
                // Bitmap bitmap = data.getParcelableExtra(DECODED_BITMAP_KEY);
            }
        } else if (resultCode == RESULT_OK) {
            gpu.doRequest(requestCode, resultCode, data);
            if (gpu.is_get_photo(requestCode)) {

                try {
                    String avatar_path = gpu.getPhotoPath();
//					Toast.makeText(getApplicationContext(),photo_type+"ok"+avatar_path,
//							Toast.LENGTH_SHORT).show();
                    final String base64 = ImageUtils.encodeBase64File(avatar_path);
                    this.appView.getView().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            webInvoke.getCamraImageCallback(base64, num, photo_type);
                        }
                    }, 1000);

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);

        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    public void imageChoose(String type, String num) {
        this.num = num;
        this.photo_type = type;
        gpu.imageChooseItem(type, "选择图片", new CharSequence[]{"从相册选择", "拍照"});
    }


    public void share(int platform, String title, String content, String url, String imgurl,
                      String pageId) {

        UMImage image = null;
        image = new UMImage(this, imgurl);
        share_pageId = pageId;
        SHARE_MEDIA share_MEDIA = SHARE_MEDIA.WEIXIN;
        switch (platform) {
            case 1:
                share_MEDIA = SHARE_MEDIA.WEIXIN;
                break;
            case 2:
                share_MEDIA = SHARE_MEDIA.WEIXIN_CIRCLE;
                break;
            case 3:
                share_MEDIA = SHARE_MEDIA.QQ;
                break;
            case 4:
                share_MEDIA = SHARE_MEDIA.QZONE;
                break;

            default:
                break;
        }
        UMWeb umWeb = new UMWeb(url, title, content, image);
        sa.setPlatform(share_MEDIA).setCallback(mUMShareListener)
                .withMedia(umWeb)
                .share();
    }

    public void shareImage(int platform, Bitmap bmp, String pageId) {
        UMImage image = null;
        image = new UMImage(this, bmp);
        SHARE_MEDIA share_MEDIA = SHARE_MEDIA.WEIXIN;
        switch (platform) {
            case 1:
                share_MEDIA = SHARE_MEDIA.WEIXIN;
                break;
            case 2:
                share_MEDIA = SHARE_MEDIA.WEIXIN_CIRCLE;
                break;
            case 3:
                share_MEDIA = SHARE_MEDIA.QQ;
                break;
            case 4:
                share_MEDIA = SHARE_MEDIA.QZONE;
                break;

            default:
                break;
        }
        sa.setPlatform(share_MEDIA).setCallback(mUMShareListener)
                .withMedia(image)
                .share();
    }

    public void noticePushClientId(final String clientId) {
        // TODO Auto-generated method stub
        this.appView.getView().post(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                //
                webInvoke.getPushClientIdCallBack(clientId);
            }
        });
    }

    public void onEventValue(final String id, final HashMap<String, String> map) {
        this.appView.getView().post(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                if (map == null || map.isEmpty()) {
                    MobclickAgent.onEvent(BaseDroidGapActivity.this, id);
                } else {
                    MobclickAgent.onEvent(BaseDroidGapActivity.this, id, map);
                }
            }
        });
    }

    public void serchWifi(final boolean isClick) {
        this.appView.getView().post(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                WifiUtil.serchWifi(BaseDroidGapActivity.this, isClick);
            }
        });
    }
}
